﻿// -----------------------------------------------------------------------
// <copyright file="XmlLogger.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using Microsoft.Practices.Prism.Logging;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using Infrastructure.Model;

namespace Infrastructure.Utility
{
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class XmlLogger : ILoggerFacade
    {
        private XDocument document;

        public XmlLogger()
        {
            document = new XDocument( new XDeclaration( "1.0", "utf-8", "yes" ), new XElement( "entries" ) );
        }

        public void Log( string message, Category category, Priority priority )
        {
            document.Element( "entries" ).Add
                       ( new XElement
                            ( "entry",
                                new XElement( "message", message ),
                                new XElement( "category", category ),
                                new XElement( "priority", priority )
                            )
                        );

            this.SaveLogFile();
        }

        private void SaveLogFile()
        {
            //using ( IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication() )
            //{
            //    using ( IsolatedStorageFileStream isoStream =
            //        new IsolatedStorageFileStream( Constants.LogOutputName, FileMode.Create, isoStore ) )
            //    {
            //        this.document.Save( isoStream );
            //    }
            //}

            this.document.Save( Constants.sDirLogFile + Constants.sLogFileOutputName );
        }

        public static string ReadLogFile()
        {
            string contents;
            //using ( IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication() )
            //{
            //    using ( StreamReader reader =
            //            new StreamReader( isoStore.OpenFile( Constants.sLogFileOutputName,
            //                FileMode.Open, FileAccess.Read ) ) )
            //    {
            //        contents = reader.ReadToEnd();
            //    }
            //}
            using ( StreamReader reader = new StreamReader( Constants.sDirLogFile + Constants.sLogFileOutputName) ) 
            {
                contents = reader.ReadToEnd();
            }

            return contents;
        }

    }
}
